//#define _WINSOCK_DEPRECATED_NO_WARNINGS
#pragma warning(disable:4996)
#include <iostream>
#include <cstring>
#include <WinSock2.h>
#include <string>
using namespace std;

#pragma comment(lib, "ws2_32.lib")


uint16_t serverport = 8080;
string serverip = "1.117.233.196";
int main()
{

	WSAData wsd;           //初始化信息

	//启动Winsock
	if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) {/*进行WinSocket的初始化,
		windows 初始化socket网络库，申请2，2的版本，windows socket编程必须先初始化。*/
		cout << "WSAStartup Error = " << WSAGetLastError() << endl;
		return 0;
	}
	else {
		cout << "WSAStartup Success" << endl;
	}


	SOCKET csock = socket(AF_INET, SOCK_DGRAM, 0);
	if (csock == SOCKET_ERROR) {
		cout << "socket Error = " << WSAGetLastError() << endl;
		return 1;
	}
	else
	{
		cout << "socket Success" << endl;
	}

	struct sockaddr_in server;
	memset(&server, 0, sizeof(server));
	server.sin_family = AF_INET;
	server.sin_port = htons(serverport);
	server.sin_addr.s_addr = inet_addr(serverip.c_str());
#define NUM 1024
	char inbuffer[NUM];
	string line;
	while (true)
	{
		cout << "Please Enter# ";
		getline(cin, line);
		int n = sendto(csock, line.c_str(), line.size(), 0, (struct sockaddr*)&server, sizeof(server));
		if (n < 0)
		{
			cerr << "sendto error!" << endl;
			break;
		}

		struct sockaddr_in peer;
		int peerlen = sizeof(peer);
		// 收取数据
		inbuffer[0] = 0;// C风格的清空
		recvfrom(csock, inbuffer, sizeof(inbuffer), 0, (struct sockaddr*)&peer, &peerlen);
		if (n > 0)
		{
			inbuffer[n] = 0;
			cout << "server 返回的消息是# " << inbuffer << endl;
		}
		else break;

	}



	closesocket(csock);
	WSACleanup();

	return 0;
}
